package com.fish.start.animation.threads;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

import com.fish.start.animation.AnimationSet;
import com.fish.start.animation.callback.CanvasDrawInterface;
import com.fish.start.animation.global.Global;
import com.fish.start.animation.views.FishView;

public class ConsumerAnimationThread implements Runnable{
	
	private static final String tag = ConsumerAnimationThread.class.getSimpleName();
	private AnimationSet mAnimations;
	public SurfaceHolder mSurfaceHolder;
	private FishView mFishView;
	public int mSleep;
	public CanvasDrawInterface mCanvasDrawInterface;
	private boolean mDestory;
	private boolean mDraw;
	public boolean mIsActive;
	public ConsumerAnimationThread(AnimationSet aAnimationSet,SurfaceHolder aSurfaceHolder,
			CanvasDrawInterface acdi,FishView aFishView){
		mAnimations = aAnimationSet;
		mSurfaceHolder = aSurfaceHolder;
		mCanvasDrawInterface = acdi;
		mFishView = aFishView;
	}
	@Override
	public void run() {
		Canvas aCanvas = null;
		while (!mDestory) {
			try {
				if(!mDraw){
					Thread.sleep(100);
					continue ;
				}
				if(mAnimations.mStopProduce && !mAnimations.hasAnimation()){
					mDraw = false;
					mCanvasDrawInterface.onStop();
					continue;
				}
				if(mAnimations.mStopProduce && mAnimations.onlyOneAnimation()){
					Global.getInstance().putLastAinmation(mAnimations.getmAnimations().get(0));
				}
				synchronized (this) {
					aCanvas = mSurfaceHolder.lockCanvas(null);
					if(null==aCanvas)continue;
					try {
						mCanvasDrawInterface.drawSelf(aCanvas);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (aCanvas != null)
							mSurfaceHolder.unlockCanvasAndPost(aCanvas);
					}
				}
			} catch (Exception e) {
				mDraw = false;
				mFishView.handlerException(e);
			}
		}
		if(mDestory){mCanvasDrawInterface.onDestory();}
	}
	public void start(){
		mDraw = true;
	}
	public void stop(){
		mDraw = false;
	}
	public void destory(){
		mDestory = true;
	}

}
